package adb;

import static adb.ADBView.jTextAreaStatus;
import static adb.ADBView.output;
import static adb.ADBView.screenShotSuccessStatus;
import static adb.ADBView.screenWidth;
import com.android.ddmlib.AndroidDebugBridge;
import com.android.ddmlib.IDevice;
import com.android.ddmlib.RawImage;
import java.awt.FlowLayout;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.TimeZone;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingWorker;

public class screenShot extends SwingWorker<Void, String> implements ClipboardOwner{

    public static int rawImageWidth;
    public static int rawImageHeight;
    public static int frameWidth100;
    public static int frameHeight100;
    public static int frameWidth50;
    public static int frameHeight50;
    public static int frameWidth75;
    public static int frameHeight75;
    public static AndroidDebugBridge bridge = AndroidDebugBridge.createBridge();
    public int angle=0;
    BufferedImage imgInputDefault;
    BufferedImage rotateImage50;
    BufferedImage rotateImage75;
    BufferedImage rotateImage100;
    IDevice device0;
    public int currentJlabelUse=100;//100% and vertical
    public static final JFileChooser fileChooser = new JFileChooser();
    @Override
    protected Void doInBackground() throws Exception {
        //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        AndroidDebugBridge.init(false /* debugger support */);
        screenShotSuccessStatus=0;
        int count = 0;
        while (bridge.hasInitialDeviceList() == false) {
            try {
                Thread.sleep(100);
                count++;output = output + "Connect..." + count + "\n";
                jTextAreaStatus.setText(output);
            } catch (InterruptedException ex) {
                jTextAreaStatus.setText(output = output + ex + "----ex18\n");
            }
            if (count > 10) {
                jTextAreaStatus.setText(output = output + "Timeout getting device list!\n");
            }
        }
        creationFrameScreenShot(getScreenShot());
        screenShotSuccessStatus=1;
        return null;
    }
    public void creationFrameScreenShot(BufferedImage img){
        imgInputDefault = img;
org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(adb.ADBApp.class).getContext().getResourceMap(ADBView.class);
//        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(adb.ADBApp.class).getContext().getResourceMap(ADBView.class);
        final JFrame framess = new JFrame();
        setWidthHeight();
        framess.setSize(frameWidth100, frameHeight100);
        framess.setPreferredSize(new java.awt.Dimension(frameWidth100, frameHeight100));
        framess.setLocation(screenWidth/2-frameWidth100/2, 0);
        JPanel buttonPanel = new JPanel();
        buttonPanel.setSize(500,30);
        buttonPanel.setPreferredSize(new java.awt.Dimension(500,30));
//        buttonPanel.setBorder(javax.swing.BorderFactory.createEtchedBorder(resourceMap.getColor("mainPanel.border.highlightColor2"), resourceMap.getColor("mainPanel.border.shadowColor2")));
        JButton refresh = new JButton("Refresh");
        
        JButton rotate = new JButton("Rotate");
        JButton save = new JButton("Save");
        JButton copy = new JButton("Copy");
        JButton zoom100 = new JButton("100%");
        JButton zoom50 = new JButton("50%");
        JButton zoom75 = new JButton("75%");
        JButton close = new JButton("Close");
        refresh.setFont(resourceMap.getFont("All.font"));
        refresh.setMnemonic('r');
        
        rotate.setFont(resourceMap.getFont("All.font"));
        save.setFont(resourceMap.getFont("All.font"));
        save.setMnemonic('s');
        
        copy.setFont(resourceMap.getFont("All.font"));
        zoom50.setFont(resourceMap.getFont("All.font"));
        zoom75.setFont(resourceMap.getFont("All.font"));
        close.setFont(resourceMap.getFont("All.font"));
        zoom100.setFont(resourceMap.getFont("All.font"));
        final JLabel imageLabel100 = new JLabel();
        final JLabel imageLabel75 = new JLabel();
        final JLabel imageLabel50 = new JLabel();
        
        refresh.setSize(200, 30);
        rotate.setSize(200, 30);
        save.setSize(200, 30);
        copy.setSize(200, 30);
        zoom100.setSize(200, 30);
        zoom50.setSize(200, 30);
        zoom75.setSize(200, 30);
        close.setSize(200, 30);
        
        imageLabel50.setIcon(new ImageIcon(zoomImage(imgInputDefault,50)));
        imageLabel75.setIcon(new ImageIcon(zoomImage(imgInputDefault,75)));
        imageLabel100.setIcon(new ImageIcon(imgInputDefault));
        framess.setResizable(false);
        framess.getContentPane().setLayout(new FlowLayout());
        framess.setTitle("Screen Shot");
        
        buttonPanel.add(refresh);
        buttonPanel.add(rotate);
        buttonPanel.add(save);
        buttonPanel.add(copy);
        buttonPanel.add(zoom100);
        buttonPanel.add(zoom75);
        buttonPanel.add(zoom50);
        buttonPanel.add(close);
        framess.getContentPane().add(buttonPanel);
        
        framess.getContentPane().add(imageLabel100);
        framess.setVisible(true);

        refresh.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                imgInputDefault=getScreenShot();
                currentJlabelUse=100;
                imageLabel50.setIcon(new ImageIcon(rotateImage50));
                imageLabel75.setIcon(new ImageIcon(rotateImage75));
                imageLabel100.setIcon(new ImageIcon(rotateImage100));
                
            }
        });
        zoom100.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                framess.remove(imageLabel50);
                framess.remove(imageLabel75);
                currentJlabelUse=100;
                setWidthHeight();
                framess.setSize(frameWidth100, frameHeight100);
                framess.setPreferredSize(new java.awt.Dimension(frameWidth100, frameHeight100));
                framess.setLocation(screenWidth/2-frameWidth100/2, 0);
                framess.add(imageLabel100);
                framess.pack();
                framess.validate();
            }
        });
        zoom75.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                framess.remove(imageLabel100);
                framess.remove(imageLabel50);
                currentJlabelUse=75;//System.out.print("angle="+angle+"\n");
//                if(newImageWidth75<630)newImageWidth75=630;
//                if(newImageHeight75<630)newImageHeight75=630;
                setWidthHeight();
                framess.setSize(frameWidth75, frameHeight75);
                framess.setPreferredSize(new java.awt.Dimension(frameWidth75, frameHeight75));
                framess.setLocation(screenWidth/2-frameWidth75/2, 0);
                framess.add(imageLabel75);
                framess.pack();framess.validate();
            }
        });
        zoom50.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                framess.remove(imageLabel100);
                framess.remove(imageLabel75);
                currentJlabelUse=50;
//                if(newImageWidth50<630)newImageWidth50=630;
//                if(newImageHeight50<630)newImageHeight50=630;
                //System.out.print("angle="+angle+"\n");
                setWidthHeight();
                framess.setSize(frameWidth50, frameHeight50);
                framess.setPreferredSize(new java.awt.Dimension(frameWidth50, frameHeight50));
                framess.setLocation(screenWidth/2-frameWidth50/2, 0);
                framess.add(imageLabel50);
                framess.pack();framess.validate();
            }
        });
        close.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
               framess.dispose();
            }
        });
        save.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Calendar localCalendar = Calendar.getInstance(TimeZone.getDefault());
                int day = localCalendar.get(Calendar.DAY_OF_MONTH);
                int month = localCalendar.get(Calendar.MONTH)+1;
                int year = localCalendar.get(Calendar.YEAR);
                int hour = localCalendar.get(Calendar.HOUR);
                int minute = localCalendar.get(Calendar.MINUTE);
                int second = localCalendar.get(Calendar.SECOND);
                //System.out.print(device0+"_"+year+month+day+"_"+hour+minute+second+".png");
                File fileName= new File(device0+"_"+year+month+day+"_"+hour+minute+second+".png");
                fileChooser.setSelectedFile(fileName);
                fileChooser.showSaveDialog(null);
                try {
                    if(currentJlabelUse==100)
                        ImageIO.write(rotateImage100, "png", fileChooser.getSelectedFile());
                    if(currentJlabelUse==75)
                        ImageIO.write(rotateImage75, "png", fileChooser.getSelectedFile());
                    if(currentJlabelUse==50)
                        ImageIO.write(rotateImage50, "png", fileChooser.getSelectedFile());
                } catch (IOException ex) {
                    jTextAreaStatus.setText(ex+"----ex20\n");
                }
            }
        });
        copy.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if(currentJlabelUse==100)
                    CopyImagetoClipBoard(rotateImage100);
                if(currentJlabelUse==75)
                    CopyImagetoClipBoard(rotateImage75);
                if(currentJlabelUse==50)
                    CopyImagetoClipBoard(rotateImage50);
            }
        });
        rotate.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
               angle = angle+1;
               if(angle==4)angle=0;
               //System.out.print("angle="+angle+"\n");
               //int frameHeight = framess.getHeight();
               //int frameWidth = framess.getWidth();
               rotateImage50 = rotateImage(zoomImage(imgInputDefault,50),angle);
               rotateImage75 = rotateImage(zoomImage(imgInputDefault,75),angle);
               rotateImage100 = rotateImage(imgInputDefault,angle);
               imageLabel50.setIcon(new ImageIcon(rotateImage50));
               imageLabel75.setIcon(new ImageIcon(rotateImage75));
               imageLabel100.setIcon(new ImageIcon(rotateImage100));
               setWidthHeight();
                if(currentJlabelUse==100)
                {
                framess.setSize(frameWidth100, frameHeight100);
                //framess.setPreferredSize(new java.awt.Dimension(frameWidth100, frameHeight100));
                framess.setLocation(screenWidth/2-frameWidth100/2, 0);
                }
                if(currentJlabelUse==75)
                {
                framess.setSize(frameWidth75, frameHeight75);
                //framess.setPreferredSize(new java.awt.Dimension(frameWidth100, frameHeight100));
                framess.setLocation(screenWidth/2-frameWidth75/2, 0);
                }
                if(currentJlabelUse==50)
                {
                framess.setSize(frameWidth50, frameHeight50);
                //framess.setPreferredSize(new java.awt.Dimension(frameWidth100, frameHeight100));
                framess.setLocation(screenWidth/2-frameWidth50/2, 0);
                }
               
               
               //framess.setPreferredSize(new java.awt.Dimension(frameHeight, frameWidth));
            }
        });
    }
    public BufferedImage getScreenShot(){
        
        IDevice[] devices = bridge.getDevices();
        RawImage rawImage = null;
        device0 = devices[0];
        try {
            rawImage = device0.getScreenshot();
            rawImageHeight = rawImage.height;
            rawImageWidth= rawImage.width;
        } catch (IOException ex) {
            jTextAreaStatus.setText(ex + "----ex17\n");
        }
        BufferedImage image = new BufferedImage(rawImageWidth,rawImageHeight,BufferedImage.TYPE_INT_ARGB);
        int index = 0;
        int IndexInc = rawImage.bpp >> 3;
        for (int y = 0; y < rawImage.height; y++) {
            for (int x = 0; x < rawImage.width; x++) {
                int value = rawImage.getARGB(index);
                index += IndexInc;
                image.setRGB(x, y, value);
            }
        }
        imgInputDefault=image;
        rotateImage50 = rotateImage(zoomImage(imgInputDefault,50),angle);
        rotateImage75 = rotateImage(zoomImage(imgInputDefault,75),angle);
        rotateImage100 = rotateImage(imgInputDefault,angle);
//        rotateImage100=image;
//        rotateImage75=zoomImage(image,75);
//        rotateImage50=zoomImage(image,50);
        
        return image;
    }
    public static BufferedImage zoomImage(BufferedImage imgInput,int ratio){
        int newImageWidth=rawImageWidth*ratio/100;
        int newImageHeight=rawImageHeight*ratio/100;
        BufferedImage imgOutput = new BufferedImage(newImageWidth , newImageHeight,BufferedImage.TYPE_INT_ARGB );
        Graphics2D g = imgOutput.createGraphics();
        g.drawImage(imgInput, 0, 0, newImageWidth , newImageHeight , null);
        g.dispose();
        
        return imgOutput;
    }
    public static BufferedImage rotateImage(BufferedImage image, int numquadrants) {
      int w0 = image.getWidth();
    int h0 = image.getHeight();
    int w1 = w0;
    int h1 = h0;
    int centerX = w0 / 2;
    int centerY = h0 / 2;
    if (numquadrants % 2 == 1) {
        w1 = h0;
        h1 = w0;
    }
    if (numquadrants % 4 == 1) {
        centerX = h0 / 2;
        centerY = h0 / 2;
    } else if (numquadrants % 4 == 3) {
        centerX = w0 / 2;
        centerY = w0 / 2;
    }
    AffineTransform affineTransform = new AffineTransform();
    affineTransform.setToQuadrantRotation(numquadrants, centerX, centerY);
    AffineTransformOp opRotated = new AffineTransformOp(affineTransform,
            AffineTransformOp.TYPE_BILINEAR);
    BufferedImage transformedImage = new BufferedImage(w1, h1,
            image.getType());
    transformedImage = opRotated.filter(image, transformedImage);

    return transformedImage;
   }
    public void CopyImagetoClipBoard(BufferedImage i) {
            TransferableImage trans = new TransferableImage( i );
            Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
            c.setContents( trans, this );
    }
    public void lostOwnership( Clipboard clip, Transferable trans ) {
        System.out.println( "Lost Clipboard Ownership" );
        jTextAreaStatus.setText("Lost Clipboard Ownership\n");
    }
    public class TransferableImage implements Transferable {

        Image i;

        public TransferableImage( Image i ) {
            this.i = i;
        }

        public Object getTransferData( DataFlavor flavor )
        throws UnsupportedFlavorException, IOException {
            if ( flavor.equals( DataFlavor.imageFlavor ) && i != null ) {
                return i;
            }
            else {
                throw new UnsupportedFlavorException( flavor );
            }
        }

        public DataFlavor[] getTransferDataFlavors() {
            DataFlavor[] flavors = new DataFlavor[ 1 ];
            flavors[ 0 ] = DataFlavor.imageFlavor;
            return flavors;
        }

        public boolean isDataFlavorSupported( DataFlavor flavor ) {
            DataFlavor[] flavors = getTransferDataFlavors();
            for ( int j = 0; j < flavors.length; j++ ) {
                if ( flavor.equals( flavors[ j ] ) ) {
                    return true;
                }
            }

            return false;
        }
    }
    public void setWidthHeight(){

            if(angle%2==0){
                frameWidth50 = rawImageWidth/2+40;
                frameHeight50 = rawImageHeight/2+80;
                frameWidth75 = rawImageWidth*75/100+40;;
                frameHeight75 = rawImageHeight*75/100+80;
                frameWidth100=rawImageWidth+40;
                frameHeight100=rawImageHeight+80;
                if(frameWidth50<500)frameWidth50 = 500;
                if(frameWidth75<500)frameWidth75 = 500;
                if(frameWidth100<500)frameWidth100=500;


            }else{
                frameWidth50 = rawImageHeight/2+40;
                frameHeight50 = rawImageWidth/2+80;
                frameWidth75 = rawImageHeight*75/100+40;;
                frameHeight75 = rawImageWidth*75/100+80;
                frameWidth100=rawImageHeight+40;
                frameHeight100=rawImageWidth+80;
                if(frameWidth50<500)frameWidth50 = 500;
                if(frameWidth75<500)frameWidth75 = 500;
                if(frameWidth100<500)frameWidth100=500;
            }
    
    }
}
